package com.demo.security.access.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.util.Assert;

import com.demo.security.access.AfterLogicInvocation;
import com.demo.security.access.AfterLogicManager;
import com.demo.security.access.LogicAttribute;
import com.demo.security.core.SecurityMessageSource;

/**
 * 抽象方法访问的后置逻辑管理器
 * 管理器管理后置逻辑调用其
 * 处理方法访问(调用)后的逻辑处理
 * 
 * @author ryuu.kk
 *
 */
public abstract class AbstractAfterLogicManager<T> implements AfterLogicManager, InitializingBean, MessageSourceAware {

	/**
	 * Log日志
	 */
	protected final Log logger = LogFactory.getLog(getClass());

	/**
	 * 方法调用处理类列表
	 */
	private List<AfterLogicInvocation<T>> afterInvocations;
	
	/**
	 * 国际化消息资源访问对象
	 */
	protected MessageSourceAccessor messages = SecurityMessageSource.getAccessor();
	
	/**
	 * 构造函数
	 * @param logicInvocations List<AccessLogicInvocation<T>>
	 */
	public AbstractAfterLogicManager(List<AfterLogicInvocation<T>> afterInvocations) {
		this.afterInvocations = afterInvocations;
	}
	
	@Override
	public boolean supports(LogicAttribute attribute) {
		if (afterInvocations != null) {
			for (AfterLogicInvocation<T> invoker : this.afterInvocations) {
				if (invoker.supports(attribute)) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		if (afterInvocations != null) {
			for (AfterLogicInvocation<T> invoker : this.afterInvocations) {
				if (invoker.supports(clazz)) {
					return true;
				}
			}
		}
		return false;
	}

	public List<AfterLogicInvocation<T>> getAfterInvocations() {
		return afterInvocations;
	}

	@Override
	public void setMessageSource(MessageSource messageSource) {
		this.messages = new MessageSourceAccessor(messageSource);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//Assert.notEmpty(this.afterInvocations, "A list of AfterLogicInvocation is required");
		Assert.notNull(this.messages, "A message source must be set");
	}
}
